package com.banciyuan.bcywebview.biz.groupdetail.info;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.groupdetail.AutoComplateAdapter;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.PostCore;
import de.greenrobot.daoexample.model.TagDetail;
import de.greenrobot.daoexample.model.Team;

/**
 * Created by squall on 2015/8/26.
 */
public class EditTagActivity extends BaseActivity implements View.OnClickListener {

    private Team team;
    private TextView save_work;
    private FlowView tag_area;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private LayoutInflater inflater;
    private List<TagDetail> tlist;
    private RelativeLayout top_line;
    private String mGid;
    private RequestQueue queue;
    private String work = "";
    private List<String> slist = new ArrayList<String>();
    private AutoComplateAdapter adapter;
    private AutoCompleteTextView auto_text;
    private TextView save_btn;
    private EditText tag_add_et;
    private TextView save_btn_gray;
    private boolean show_flag = false;
    private boolean delete_flag = false;
    private boolean add_flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_group);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(work)) {
            save_work.setVisibility(View.VISIBLE);
            save_btn_gray.setVisibility(View.GONE);
        } else {
            save_work.setVisibility(View.GONE);
            save_btn_gray.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        team = (Team) intent.getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        mGid = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        inflater = LayoutInflater.from(this);
        if (team != null) {
            tlist = team.getTags();
            work = team.getWork();
        }
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.edittag));
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                save_change();
                finish();
            }

            @Override
            public void onActionClick(int id) {

            }
        });
    }

    @Override
    protected void initUi() {
        save_work = (TextView) findViewById(R.id.acg_group_save);
        tag_area = (FlowView) findViewById(R.id.add_tag_lv);
        save_work.setVisibility(View.VISIBLE);
        auto_text = (AutoCompleteTextView) findViewById(R.id.edit_group_autotv);
        top_line = (RelativeLayout) findViewById(R.id.linearLayout);
        save_btn = (TextView) findViewById(R.id.tag_group_add);
        tag_add_et = (EditText) findViewById(R.id.tag_add_et);
        save_btn_gray = (TextView) findViewById(R.id.acg_group_save_vaild);
        if (!TextUtils.isEmpty(team.getWork())) {
            auto_text.setText(team.getWork());
        }
        if (!tlist.isEmpty()) {
            tag_area.setVisibility(View.VISIBLE);
        } else {
            tag_area.setVisibility(View.GONE);
        }
        if (Boolean.valueOf(team.getIsCreator())) {
            top_line.setVisibility(View.VISIBLE);
        } else {
            top_line.setVisibility(View.GONE);
        }
        save_work.setVisibility(View.GONE);
        save_btn_gray.setVisibility(View.VISIBLE);
        findViewById(R.id.rl_recommend).setVisibility(View.GONE);
    }

    @Override
    protected void initAction() {
        for (TagDetail t : tlist) {
            addSingleTag(t);
        }
        auto_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                show_flag = hasFocus;
            }
        });

        final IGetAutoComplate iGetAutoComplate = new IGetAutoComplate() {
            @Override
            public void getComplateList(String s, boolean show) {
                dealJson(s);
            }
        };

        auto_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    auto_text.dismissDropDown();
                } else {
                    getCompleteWork(editable, iGetAutoComplate);
                }

                save_work.setVisibility(View.VISIBLE);
                save_btn_gray.setVisibility(View.GONE);
            }
        });

        auto_text.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                tag_add_et.requestFocus();
            }
        });

        tag_add_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    addtagTest();
                }
                return true;
            }
        });

        save_btn.setOnClickListener(this);
        save_work.setOnClickListener(this);
    }

    private void getCompleteWork(Editable editable, IGetAutoComplate iGetAutoComplate) {
        String url = HttpUtils.BASE_URL + CoreApi.getGetcorelist();
        AutoComplateHelper autoHelper = new AutoComplateHelper(this, iGetAutoComplate, "");
        autoHelper.findServerTitle(editable, true, url);
    }

    private void deleteTag(final TagDetail tegDetail) {
        delete_flag = true;
        String url = HttpUtils.BASE_URL + GroupApi.getDeletetag();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(EditTagActivity.this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.TAG_NAMED, tegDetail.getTag_name()));
        paramsList.add(new BcyPair(HttpUtils.TAG_ID, tegDetail.getTag_id()));

        HashMap<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditTagActivity.this)) {
                    for (int i = 0; i < tag_area.getChildCount(); i++) {
                        View view = tag_area.getChildAt(i);
                        String tag_id = (String) view.getTag();
                        if (tag_id.equals(tegDetail.getTag_id())) {
                            tag_area.removeView(view);
                            tlist.remove(i);
                            break;
                        }
                    }
                }
                delete_flag = false;
                setAreaVisiable();
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                delete_flag = false;
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(requestParam);

    }

    private void addTag(TagDetail tegDetail) {
        if (!UserDataHelper.ifLogin(this)) {
            MyToast.show(this, getString(R.string.loginfirst));
            return;
        }
        add_flag = true;
        String url = HttpUtils.BASE_URL + GroupApi.getAddtag();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(EditTagActivity.this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.TAG_NAMED, tegDetail.getTag_name()));
        HashMap<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditTagActivity.this)) {
                    try {
                        JSONObject jsonobject = new JSONObject(s);
                        JSONObject jsonresult = jsonobject.getJSONObject("data");
                        TagDetail tagdetail = new TagDetail();
                        tagdetail.setTag_id(jsonresult.getString("tag_id"));
                        tagdetail.setTag_name(jsonresult.getString("tag_name"));
                        tagdetail.setCover(jsonresult.getString("cover"));
                        tagdetail.setCan_edit(true);
                        addSingleTag(tagdetail);
                        tlist.add(tagdetail);
                        setAreaVisiable();
                        tag_add_et.setText("");
                    } catch (JSONException e) {
                        add_flag = false;
                    }
                }
                add_flag = false;
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                add_flag = false;
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(requestParam);
    }

    private void modifyWork() {
        String url = HttpUtils.BASE_URL + GroupApi.doUpdatework();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(EditTagActivity.this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.GID, mGid));
        paramsList.add(new BcyPair(HttpUtils.GROUP_WORK, work));
        HashMap<String, String> map = HttpUtils.getData(paramsList);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditTagActivity.this)) {
                    MyToast.show(EditTagActivity.this, getString(R.string.modify_work_succ));
                    work = auto_text.getText().toString();
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        PostCore postCore = gson.fromJson(result.toString(), new TypeToken<PostCore>() {
                        }.getType());
                        team.setWork(postCore.getName());
                        team.setId(postCore.getId());
                        team.setCover(postCore.getCover());
                        team.setIntro(postCore.getIntro());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MyToast.show(EditTagActivity.this, getString(R.string.edit_work_fail));
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(requestParam);
    }

    private void save_change() {
        Intent intent = new Intent();
        intent.putExtra("team", team);
        setResult(RESULT_OK, intent);
    }

    private void dealJson(String s) {
        if (StatusCodeUtils.dealStatusCode(s, this)) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                adapter = new AutoComplateAdapter(slist, this, auto_text.getText().toString());
                auto_text.setAdapter(adapter);
            } catch (Exception e) {

            }
        }
        if (show_flag) {
            auto_text.showDropDown();
        }
    }

    private void addSingleTag(final TagDetail t) {
        View view = null;
        TextView tag = null;
        if (!t.isCan_edit()) {
            view = inflater.inflate(R.layout.tag_margin_blue, null);
            tag = (TextView) view.findViewById(R.id.single_tag);
        } else {
            view = inflater.inflate(R.layout.tag_blue_cancel, null);
            tag = (TextView) view.findViewById(R.id.single_tag_cancel);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!delete_flag) {
                        deleteTag(t);
                    }
                }
            });
        }
        tag.setText(t.getTag_name());
        view.setTag(t.getTag_id());
        tag_area.addView(view);
        add_flag = false;

    }

    private void setAreaVisiable() {
        if (tlist.isEmpty()) {
            tag_area.setVisibility(View.GONE);
        } else {
            tag_area.setVisibility(View.VISIBLE);
        }
    }

    private void addtagTest() {
        if (!add_flag) {
            TagDetail tagDetail = new TagDetail();
            tagDetail.setTag_name(tag_add_et.getText().toString());
            if (tag_area.getChildCount() < 5) {
                if (!TextUtils.isEmpty(tagDetail.getTag_name())) {
                    boolean flag = true;
                    for (TagDetail t : tlist) {
                        if (t.getTag_name().equals(tagDetail.getTag_name())) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        addTag(tagDetail);
                    } else {
                        MyToast.show(EditTagActivity.this, getString(R.string.label_mutli_disable));
                    }
                } else {
                    MyToast.show(EditTagActivity.this, getString(R.string.label_shoudnot_benull));
                }
            } else {
                MyToast.show(EditTagActivity.this, getString(R.string.label_five_limit));
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.acg_group_save:
                work = auto_text.getText().toString();
                modifyWork();
                break;
            case R.id.tag_group_add:
                addtagTest();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        save_change();
        super.onBackPressed();
    }
}
